package com.oig.sys.util;

import cn.hutool.core.comparator.CompareUtil;
import org.hibernate.type.Type;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

public class DataCompareUtil {

    private DataCompareUtil(){}


    public static void compareDiff(Object[] newEntity, Object[] oldEntity, String[] names, Type[] types, Map<String,Object> newValue, Map<String,Object> oldValue){
        for (int col = 0; col < oldEntity.length; col++) {
            //外键忽略处理
            if (types[col].isAssociationType()) {
                continue;
            }

            // 相等就不处理
            if ((oldEntity[col] == newEntity[col])) {
                continue;
            }

            //如不相等，则加入字符串中
            if (!compare(newEntity[col], oldEntity[col])) {
                oldValue.put(names[col], oldEntity[col]);
                newValue.put(names[col], newEntity[col]);
            }
        }
    }


    /**
     * 获取不同的值
     */
    public static void compareDiff(Object[] newEntity,  String[] names, Type[] types, Map<String,Object> diffValue) {
        for (int col = 0; col < newEntity.length; col++) {
            //外键忽略处理
            if (types[col].isAssociationType()) {
                continue;
            }
            //如不相等，则加入字符串中
            if (newEntity[col] != null ) {
                diffValue.put(names[col], newEntity[col]);
            }
        }
    }

    /**
     * 对象值比较
     */
    private static boolean compare(Object newValue, Object oldValue) {
        if (newValue instanceof BigDecimal) {
            return CompareUtil.compare((BigDecimal) newValue, (BigDecimal) oldValue) == 0;
        } else if (newValue instanceof Date) {
            return CompareUtil.compare((Date) newValue, (Date) oldValue) == 0;
        }
        if (oldValue != null && !oldValue.equals(newValue)
                || oldValue == null && newValue != null) {
            return false;
        }
        return true;
    }


}
